package com.evry.uttrekk.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.evry.uttrekk.domain.Customers;
import com.evry.uttrekk.domain.Products;
import com.evry.uttrekk.repository.CustomerDao;
import com.evry.uttrekk.repository.CustomerDaoImpl;
import com.evry.uttrekk.service.UttrekkManager;
import com.evry.uttrekk.service.UttrekkManagerImpl;

@Configuration
public class AppConfig {

	@Bean
	DataSource dataSource() {
		BasicDataSource source = new BasicDataSource();
		source.setDriverClassName("org.hsqldb.jdbcDriver");
		source.setUrl("jdbc:hsqldb:hsql://localhost");
		source.setUsername("sa");
		source.setPassword("");
		return (DataSource) source;
	}
	
	//TODO: Refactor how configuration is read! Both how it receives connection and how it maps classes. 
	@Bean
	SessionFactory sessionFactory(){
		org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration().addAnnotatedClass(Customers.class).addAnnotatedClass(Products.class);
		ServiceRegistry serviceRegistry = new
	              ServiceRegistryBuilder().applySettings
	              (configuration.configure().getProperties()).buildServiceRegistry();  
		return configuration.buildSessionFactory();
	}
	
    @Bean
    public UttrekkManager uttrekkManager() {
        return new UttrekkManagerImpl();
    }
    
    @Bean
    public CustomerDao customerDao(){
    	return new CustomerDaoImpl(sessionFactory());
    }
}
